package com.hxkcloud.patient.utils;

import java.io.BufferedOutputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.graphics.Matrix;
import android.media.ExifInterface;
import android.media.MediaMetadataRetriever;
import android.net.Uri;
import android.provider.MediaStore;

/**
 * @Description: 视频、图片工具类
 */

public class ImageVideoUtils {

    /**
     * 重新调整广告图的高度
     *
     * @param screenWidth
     * @param scaleWidth
     * @param scaleHeight 广告图尺寸
     *                    首页：750*420
     *                    社区：750*280
     *                    视频：750*280
     *                    病案：750*280
     *                    同行风采：750*280
     *                    执业：750*362
     * @return
     */
    public static int reSizeBannerHeight(int screenWidth, int scaleWidth, int scaleHeight) {
        return (screenWidth * scaleHeight) / scaleWidth;
    }

    private static final int UNCONSTRAINED = -1;

    /**
     * 根据图片地址获取图片的bitmap对象
     *
     * @param imagePath
     * @param context
     * @param isSave    是否保存图片
     * @return
     */
    public static Bitmap createBitmap(String imagePath, Context context,
                                      boolean isSave) {

        Bitmap bitmap = null;

        try {
            Options options = new Options();
            options.inJustDecodeBounds = true;
            bitmap = BitmapFactory.decodeFile(imagePath, options);
            options.inSampleSize = options.outWidth / 500 > 2 ? options.outWidth / 500
                    : 2;
            options.inJustDecodeBounds = false;
            bitmap = BitmapFactory.decodeFile(imagePath, options);
        } catch (OutOfMemoryError e) {
            e.printStackTrace();
            return null;
        }

        return bitmap;
    }

    /**
     * 保存bitmap到对应的文件夹下
     *
     * @param photo
     * @param spath
     */
    public static void saveImage(Bitmap photo, String spath) {
        try {
            BufferedOutputStream bos = new BufferedOutputStream(
                    new FileOutputStream(spath, false));
            photo.compress(Bitmap.CompressFormat.JPEG, 100, bos);
            bos.flush();
            bos.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            if (!photo.isRecycled()) {
                photo.recycle();
            }
        }
    }


    /**
     * 重新调整图片大小
     *
     * @param bitmap
     * @param maxSize
     * @return
     */
    public static final Bitmap resizeBitmap(Bitmap bitmap, int maxSize) {
        int srcWidth = bitmap.getWidth();
        int srcHeight = bitmap.getHeight();
        int width = maxSize;
        int height = maxSize;
        boolean needsResize = false;
        if (srcWidth > srcHeight) {
            if (srcWidth > maxSize) {
                needsResize = true;
                height = ((maxSize * srcHeight) / srcWidth);
            }
        } else {
            if (srcHeight > maxSize) {
                needsResize = true;
                width = ((maxSize * srcWidth) / srcHeight);
            }
        }
        if (needsResize) {
            Bitmap retVal = Bitmap.createScaledBitmap(bitmap, width, height,
                    true);
            return retVal;
        } else {
            return bitmap;
        }
    }

    public static Bitmap doImageBitmap(InputStream in) {
        Bitmap bitmap = null;
        Options options = null;
        final int BUFFER_SIZE = 2048;
        if (in == null) {
            return null;
        }
        try {
            ByteArrayOutputStream outStream = new ByteArrayOutputStream();
            byte[] bytes = new byte[BUFFER_SIZE];
            int len = -1;
            while ((len = in.read(bytes)) != -1) {
                outStream.write(bytes, 0, len);
                outStream.flush();
            }
            byte[] data = new byte[outStream.toByteArray().length];
            data = outStream.toByteArray();
            outStream.close();
            in.close();
            options = new Options();
            // 这里设置true的时候，decode时候Bitmap返回的为空， 将图片宽高读取放在Options里.
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeByteArray(data, 0, data.length, options);
            // 计算浏览列表显示图片的缩放比例值
            options.inSampleSize = Utils.computeSampleSize(options, -1,
                    (400 * 400) * 2);
            options.inJustDecodeBounds = false;
            bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,
                    options);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return recycleBitmap(bitmap);
    }

    public static Bitmap recycleBitmap(Bitmap bitmap) {
        if (bitmap == null) {
            return bitmap;
        }
        Bitmap newBitmap = bitmap.copy(Config.ARGB_8888, false);
        if (newBitmap != bitmap) {
            bitmap.recycle();
        }
        return newBitmap;
    }

    /**
     * 拍照、视频保存位置，有SD卡就返回SD卡目录，没有则返回手机存储目录
     */
    public static String getDataCacheDir(Context mContext) {
        File externalFilesDir = mContext.getExternalFilesDir("/dataCache");
        if (externalFilesDir != null) {
            return externalFilesDir.getAbsolutePath();
        } else {
            return mContext.getDir("dataCache", 0).getAbsolutePath();
        }
    }

    /**
     * 把图片Uri转换为文件路径
     *
     * @param uri
     * @return
     */
    public static String getImagePathForUri(Uri uri, Context context) {
        String[] proj = {MediaStore.Images.Media.DATA};
        Cursor cursor = ((Activity) context).managedQuery(uri, proj, null, null, null);
        if (cursor == null) {
            return null;
        }
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    /**
     * 根据uri获取图片名称
     *
     * @param contentUri
     * @param context
     * @return
     */
    public static String getImageDisplayNameForUri(Uri contentUri, Context context) {
        String[] proj = {MediaStore.Images.Media.DISPLAY_NAME};
        Cursor cursor = ((Activity) context).managedQuery(contentUri, proj,
                null, null, null);
        if (cursor == null) {
            return null;
        }
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DISPLAY_NAME);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    /**
     * 把视频Uri转换为文件路径
     *
     * @param uri
     * @return
     */
    public static String getVideoPathForUri(Uri uri, Context context) {
        String[] proj = {MediaStore.Video.Media.DATA};
        Cursor cursor = ((Activity) context).managedQuery(uri, proj, null, null, null);
        if (cursor == null) {
            return null;
        }
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Video.Media.DATA);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    /**
     * 根据uri获取图片名称
     *
     * @param contentUri
     * @param context
     * @return
     */
    public static String getVideoDisplayNameForUri(Uri contentUri, Context context) {
        String[] proj = {MediaStore.Video.Media.DISPLAY_NAME};
        Cursor cursor = ((Activity) context).managedQuery(contentUri, proj,
                null, null, null);
        if (cursor == null) {
            return null;
        }
        int column_index = cursor
                .getColumnIndexOrThrow(MediaStore.Video.Media.DISPLAY_NAME);
        cursor.moveToFirst();
        return cursor.getString(column_index);
    }

    /**
     * 获取上传文件信息，
     *
     * @param type     type=1: 图片文件，需要压缩图片,type=2：视频文件
     * @param filePath 文件的完整路径
     * @return
     */
    public static File getUploadFile(int type, String filePath) {

        File file = new File(filePath);
        if (!file.exists()) {
            return null;
        }
        if (type == 1) {
            Options options = new Options();
            options.inJustDecodeBounds = true;
            BitmapFactory.decodeFile(filePath, options);
            options.inSampleSize = calculateInSampleSize(options, 480, 800);
            options.inJustDecodeBounds = false;

            Bitmap newBitmap = BitmapFactory.decodeFile(filePath, options);

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            newBitmap.compress(Bitmap.CompressFormat.JPEG, 50, baos);
            byte[] b = baos.toByteArray();
        }

        return file;
    }

    //计算图片的缩放值
    public static int calculateInSampleSize(Options options, int reqWidth, int reqHeight) {
        final int height = options.outHeight;
        final int width = options.outWidth;
        int inSampleSize = 1;

        if (height > reqHeight || width > reqWidth) {
            final int heightRatio = Math.round((float) height / (float) reqHeight);
            final int widthRatio = Math.round((float) width / (float) reqWidth);
            inSampleSize = heightRatio < widthRatio ? heightRatio : widthRatio;
        }
        return inSampleSize;
    }

    /**
     * 获取视频缩略图
     *
     * @param filePath
     * @return
     */
    public static Bitmap getVideoThumbnail(String filePath) {
        Bitmap bitmap = null;
        MediaMetadataRetriever retriever = new MediaMetadataRetriever();

        try {
            retriever.setDataSource(filePath);
            bitmap = retriever.getFrameAtTime(-1);
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (RuntimeException e) {
            e.printStackTrace();
        } finally {
            try {
                retriever.release();
            } catch (RuntimeException e) {
                e.printStackTrace();
            }
        }
        return bitmap;
    }


/*********************************************************************************************************************/
    /**
     * 图片尺寸压缩
     *
     * @param
     * @param outFile 保存文件
     */
    public static void compressPicture(File pictureFile, File outFile) {
        String filePath = pictureFile.getAbsolutePath();
        FileOutputStream fos = null;
        Options op = new Options();

        Bitmap bitmap = null;
        // 开始读入图片，此时把options.inJustDecodeBounds 设回true了  
        op.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, op);
        op.inJustDecodeBounds = false;
        // 缩放图片的尺寸  
        float w = op.outWidth;
        float h = op.outHeight;
        float hh = 720f;//标准宽高
        float ww = 720f;//
        // 最长宽度或高度1024 改为720
        float be = 1.0f;
        if (w > h && w > ww) {
            be = (float) (w / ww);
        } else if (w < h && h > hh) {
            be = (float) (h / hh);
        }
        if (be <= 0) {
            be = 1.0f;//默认最小缩放比例为1，即不缩放
        } else {
            be = (int) Math.ceil((double) be);
        }
        op.inSampleSize = (int) be;// 设置缩放比例
        // 重新读入图片，注意此时已经把options.inJustDecodeBounds 设回false了  
        bitmap = BitmapFactory.decodeFile(filePath, op);
        int angle = readPictureDegree(filePath);
        if (angle > 0) {
            bitmap = toturn(bitmap);
            int desWidth = (int) (h / be);
            int desHeight = (int) (w / be);
            bitmap = Bitmap.createScaledBitmap(bitmap, desWidth, desHeight, true);
        } else {
            int desWidth = (int) (w / be);
            int desHeight = (int) (h / be);
            bitmap = Bitmap.createScaledBitmap(bitmap, desWidth, desHeight, true);
        }
        try {
            fos = new FileOutputStream(outFile);
            if (bitmap != null) {
                bitmap.compress(Bitmap.CompressFormat.JPEG, 60, fos);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }

    }
    /**
     * 对图片进行二次采样，生成缩略图
     */
    public static Bitmap createThumbnail(String fileName, int newWidth,
                                         int newHeight) {
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        // BitmapFactory.decodeResource(context.getResources(), id, options);
        BitmapFactory.decodeFile(fileName, options);
        int originalWidth = options.outWidth;
        int originalHeight = options.outHeight;
        int ratioWidth = originalWidth / newWidth;
        int ratioHeight = originalHeight / newHeight;

        options.inSampleSize = ratioHeight > ratioWidth ? ratioHeight
                : ratioWidth;
        options.inJustDecodeBounds = false;
        return BitmapFactory.decodeFile(fileName, options);
    }
    public static void compressThumbnail(File pictureFile, File outFile){
        FileOutputStream fos = null;
        String filePath = pictureFile.getAbsolutePath();
        BitmapFactory.Options options = new BitmapFactory.Options();
        options.inJustDecodeBounds = true;
        BitmapFactory.decodeFile(filePath, options);
        int originalWidth = options.outWidth;
        int originalHeight = options.outHeight;
        int newWidth = 0;
        int newHeight = 0;
        if (originalWidth > originalHeight) {

            newHeight = 720;
            newWidth = (int) (originalWidth / (originalHeight * 1.0) * 720);
        } else {
            newWidth = 720;
            newHeight = (int) ((originalHeight * 1.0) * 720 / originalWidth);
        }
        Bitmap bitmap = createThumbnail(filePath, newWidth, newHeight);
        try {
            fos = new FileOutputStream(outFile);
            if (bitmap != null) {
                bitmap.compress(Bitmap.CompressFormat.JPEG, 60, fos);
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        //final Bitmap bitmap2 = BitMapUtil.PicZoomExact(bitmap, newWidth, newHeight);
        //  final String name = System.currentTimeMillis() + ".jpg";
    }

    /**
     * 读取照片exif信息中的旋转角度
     *
     * @param path 照片路径
     * @return角度
     */
    public static int readPictureDegree(String path) {
        int degree = 0;
        try {
            ExifInterface exifInterface = new ExifInterface(path);
            int orientation = exifInterface.getAttributeInt(ExifInterface.TAG_ORIENTATION, ExifInterface.ORIENTATION_NORMAL);
            switch (orientation) {
                case ExifInterface.ORIENTATION_ROTATE_90:
                    degree = 90;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_180:
                    degree = 180;
                    break;
                case ExifInterface.ORIENTATION_ROTATE_270:
                    degree = 270;
                    break;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return degree;
    }


    public static Bitmap toturn(Bitmap img) {
        Matrix matrix = new Matrix();
        matrix.postRotate(+90); /*翻转90度*/
        int width = img.getWidth();
        int height = img.getHeight();
//        int w = 0;
//        int h = 0;
//        if (width < height) {
//            w = width;
//            h = w * width / height;
//            matrix.postScale(1, width / height);
//        } else if (width > height) {
//            h = height;
//            w = h * height / width;
//            matrix.postScale(height / width, 1);
//        } else {
//            w = width;
//            h = height;
//        }

        img = Bitmap.createBitmap(img, 0, 0, width, height, matrix, true);
        return img;
    }

}
